package main

import (
	"context"
	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"google.golang.org/grpc"
	"grpc-server/helpers"
	"grpc-server/services"
	"log"
	"net/http"
)

//http接口
func main() {
	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	//gwmux, _ := newGateway(ctx)
	// Register gRPC server endpoint
	// Note: Make sure the gRPC server is running properly and accessible
	mux := runtime.NewServeMux()
	//mux.HandleFunc("/swagger/", swagger.ServeSwaggerFile)
	//swagger.ServeSwaggerUI(mux)
	//客户端的证书校验 需要拷贝生成的客户端证书
	opts := []grpc.DialOption{grpc.WithTransportCredentials(helpers.GetClientCert())}
	err := services.RegisterHelloServiceHandlerFromEndpoint(ctx, mux, ":8085", opts)
	//注册产品服务
	_ = services.RegisterProductServiceHandlerFromEndpoint(ctx, mux, ":8085", opts)
	//注册订单服务
	_ = services.RegisterOrderSerivceHandlerFromEndpoint(ctx, mux, ":8085", opts)
	if err != nil {
		log.Fatal(err)
	}

	httpServer := &http.Server{
		Addr:    ":8080",
		Handler: mux,
	}

	err = httpServer.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}

func newGateway(ctx context.Context) (http.Handler, error) {
	opts := []grpc.DialOption{grpc.WithTransportCredentials(helpers.GetServerCert())}
	gwmux := runtime.NewServeMux()
	if err := services.RegisterHelloServiceHandlerFromEndpoint(ctx, gwmux, ":8085", opts); err != nil {
		return nil, err
	}

	return gwmux, nil
}
